package com.neusoft.neuiotms.dcom.task.maintain.job;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.neusoft.bizcore.web.utils.id.BaseIdGenerator;
import com.neusoft.neuiotms.dcom.constants.DCOMConstants;
import com.neusoft.neuiotms.dcom.dto.CMDBInstanceDTO;
import com.neusoft.neuiotms.dcom.dto.MaintainTaskDTO;
import com.neusoft.neuiotms.dcom.model.MaintainPlan;
import com.neusoft.neuiotms.dcom.model.enums.MaintainTaskSourceEnum;
import com.neusoft.neuiotms.dcom.model.enums.MaintainTaskStatusEnum;
import com.neusoft.neuiotms.dcom.repository.MaintainPlanRepository;
import com.neusoft.neuiotms.dcom.service.MaintainTaskService;
import com.neusoft.neuiotms.dcom.util.SendingMessageDcom;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MaintainTaskCreateJob extends QuartzJobBean {

    @Autowired
    private MaintainPlanRepository maintainPlanRepository;
    @Autowired
    private SendingMessageDcom sendingMessage;
    @Autowired
    private MaintainTaskService maintainTaskService;
    @Autowired
    private BaseIdGenerator maintainTaskCodeGenerator;

    @Override
    protected void executeInternal(final JobExecutionContext context) throws JobExecutionException {
        MaintainTaskCreateJob.log.info("-----------------------维护计划定时任务开始-----------------------");
        MaintainTaskCreateJob.log.info("############### 维护计划编码-> [ " + context.getJobDetail().getKey().getName() + "]");
        final MaintainPlan plan =
                this.maintainPlanRepository.findByCode(context.getJobDetail().getKey().getName());

        if (plan == null) {
            MaintainTaskCreateJob.log.info("当前无维护计划可供生成维护任务, 计划编码参数为：[" +
                    context.getJobDetail().getKey().getName() + "]");
            return;
        }

        if (StringUtils.isNotEmpty(plan.getJsonObjs())) {
            final List<CMDBInstanceDTO> iList = JSON.parseArray(plan.getJsonObjs(), CMDBInstanceDTO.class);
            if (CollectionUtils.isNotEmpty(iList)) {
                MaintainTaskDTO taskDTO = null;
                for (final CMDBInstanceDTO instance : iList) {
                    taskDTO = new MaintainTaskDTO();
                    this.createMaintainTaskDTO(plan, instance, taskDTO); // 创建任务实例
                    MaintainTaskCreateJob.log.info("################ 任务对象 -> [ " + taskDTO.getObjName() + " ]");
                    this.maintainTaskService.create(taskDTO); // 生成任务
                }
            }

            this.sendNoticeMessage(plan, iList);
        }
        MaintainTaskCreateJob.log.info("-----------------------维护计划定时任务完成-----------------------");
    }

    private void createMaintainTaskDTO(final MaintainPlan plan,
            final CMDBInstanceDTO instance,
            final MaintainTaskDTO taskDTO) {

        taskDTO.setCode(this.maintainTaskCodeGenerator.generateCode());
        taskDTO.setName(String.format(DCOMConstants.MAINTAIN_TASK_NAME, plan.getName()));

        taskDTO.setPlanCode(plan.getCode());
        taskDTO.setPlanName(plan.getName());

        taskDTO.setModelCode(instance.getSchemadef().getCode());
        taskDTO.setModelName(instance.getSchemadef().getName());

        taskDTO.setObjCode(instance.getCode());
        taskDTO.setObjName(instance.getName());

        if (plan.getRule() != null) {
            taskDTO.setSuspendService(plan.getRule().isSuspendService());
            taskDTO.setQuantifyingTime(plan.getRule().getQuantifyingTime());
        }

        taskDTO.setStatus(MaintainTaskStatusEnum.undo); // 任务状态
        taskDTO.setRule(plan.getRule());

        taskDTO.setOrgCode(plan.getOrgCode());
        taskDTO.setOrgName(plan.getOrgName());

        taskDTO.setChargeUserId(plan.getChargeUserId());
        taskDTO.setChargeUserCode(plan.getChargeUserCode());
        taskDTO.setChargeUserName(plan.getChargeUserName());

        // taskDTO.setResult(MaintainTaskResultStatus.normal);
        taskDTO.setSource(MaintainTaskSourceEnum.period);

        taskDTO.setCreateRule(false);

        taskDTO.setCreateTime(new Date());
        taskDTO.setUpdateTime(new Date());

        taskDTO.setVersion(plan.getVersion());
    }

    private void sendNoticeMessage(final MaintainPlan plan, final List<CMDBInstanceDTO> iList) {
        final List<String> nameList =
                iList.stream().map(p -> p.getName() + "(" + p.getCode() + ")").collect(Collectors.toList());
        final String objsStr = Joiner.on(",").join(nameList);

        final StringBuffer content = new StringBuffer(DCOMConstants.YOU_MAINTAIN_TASK);
        //拼消息体
        final JSONObject notice = new JSONObject();
        notice.put("appCode", "DCOM");
        notice.put("title", DCOMConstants.MAINTAIN_TASK);
        notice.put("type", Arrays.asList("notice"));

        final JSONObject system = new JSONObject();
        system.put("noticeType", DCOMConstants.PEROID_MAINTAIN_TASK);

        system.put("noticeRoute", "dcom_maintainTask");

        final JSONArray userId = new JSONArray();
        userId.add(plan.getChargeUserCode());
        system.put("users", userId);

        // 维护的设备
        content.append(DCOMConstants.MAINTAIN_OBJECT).append(objsStr)
                .append(DCOMConstants.MAINTAIN_RIGHT_MIDDLE_BRACKETS);
        system.put("content", content.toString());

        notice.put("system", system);
        this.sendingMessage.SendMsgToNotice(notice.toString());
        MaintainTaskCreateJob.log.info("发送的消息内容是： " + notice.toString());
    }

}
